import { http } from "@/utils/http";
import type { HttpResponse } from "types/request";

import { URL_PREFIX } from "./constants";

export type CtpSettings = {
  name: string;
  name_cn: string;
  user_id: string;
  password: string;
  broker_id: string;
  td_address: string;
  md_address: string;
  app_id: string;
  auth_code: string;
  broker_name_cn?: string;
};

export type TradeAppSettings = {
  name: string;
  ctp_settings_name: string;
  env_vars: Record<string, string>;
  enabled: boolean;
  trade_enabled: boolean;
  app_type: "trade" | "marketdata";
  affinity: string;
  email_enabled: boolean;
  email_address?: string | null;
};

export function getCtpSettings(name: string) {
  return http.request<HttpResponse<CtpSettings>>(
    "get",
    `${URL_PREFIX}/settings/ctp`,
    {
      params: {
        name
      }
    }
  );
}

export function searchCtpSettings(name: string) {
  return http.request<HttpResponse<CtpSettings[]>>(
    "get",
    `${URL_PREFIX}/settings/ctp/search`,
    {
      params: { name }
    }
  );
}

export function createCtpSettings(data: CtpSettings) {
  return http.request<HttpResponse<CtpSettings>>(
    "post",
    `${URL_PREFIX}/settings/ctp`,
    {
      data
    }
  );
}

export function updateCtpSettings(data: CtpSettings) {
  return http.request<HttpResponse<CtpSettings>>(
    "put",
    `${URL_PREFIX}/settings/ctp`,
    {
      data
    }
  );
}

export function getAllCtpSettings() {
  return http.request<HttpResponse<CtpSettings[]>>(
    "get",
    `${URL_PREFIX}/settings/ctp/all`
  );
}

export function getTradeAppSettings(name: string) {
  return http.request<HttpResponse<TradeAppSettings>>(
    "get",
    `${URL_PREFIX}/settings/trade_app`,
    {
      params: { name }
    }
  );
}

export function createTradeAppSettings(data: TradeAppSettings) {
  return http.request<HttpResponse<TradeAppSettings>>(
    "post",
    `${URL_PREFIX}/settings/trade_app`,
    {
      data
    }
  );
}

export function updateTradeAppSettings(data: TradeAppSettings) {
  return http.request<HttpResponse<TradeAppSettings>>(
    "put",
    `${URL_PREFIX}/settings/trade_app`,
    {
      data
    }
  );
}

export function getAllTradeAppSettings() {
  return http.request<HttpResponse<TradeAppSettings[]>>(
    "get",
    `${URL_PREFIX}/settings/trade_apps`
  );
}
